// src/screens/profile/SubscriptionScreen.tsx
import React, { useState, useEffect } from 'react';
import {
    View,
    Text,
    StyleSheet,
    ScrollView,
    TouchableOpacity,
    Alert,
    ActivityIndicator,
    Dimensions,
    Modal,
} from 'react-native';
import LinearGradient from 'react-native-linear-gradient';
import Toast from 'react-native-toast-message';
import { useSelector, useDispatch } from 'react-redux';
import { useNavigation } from '@react-navigation/native';
import {
    Product,
} from 'react-native-iap';
import { RootState, AppDispatch } from '../../store/store';
import { updateSubscription } from '../../store/slices/subscriptionSlice';
import billingService from '../../services/billingService';
import Icon from 'react-native-vector-icons/MaterialIcons';
const { width } = Dimensions.get('window');

interface PlanFeature {
    icon: string;
    text: string;
    included: boolean;
}

interface SubscriptionPlan {
    id: string;
    name: string;
    price: string;
    period: string;
    color: string[];
    popular?: boolean;
    features: PlanFeature[];
    savings?: string;
}

const SubscriptionScreen: React.FC = () => {
    const navigation = useNavigation();
    const dispatch = useDispatch<AppDispatch>();
    const { user } = useSelector((state: RootState) => state.auth);
    const { subscription } = useSelector((state: RootState) => state.subscription);

    const [products, setProducts] = useState<Product[]>([]);
    const [selectedPlan, setSelectedPlan] = useState<string>('ai_tool_premium_monthly');
    const [isLoading, setIsLoading] = useState(false);
    const [isPurchasing, setIsPurchasing] = useState(false);
    const [showFAQ, setShowFAQ] = useState(false);
    const [expandedFAQ, setExpandedFAQ] = useState<number | null>(null);

    const plans: SubscriptionPlan[] = [
        {
            id: 'free',
            name: '免费版',
            price: '¥0',
            period: '永久',
            color: ['#95a5a6', '#7f8c8d'],
            features: [
                { icon: 'chat', text: '每日10次AI对话', included: true },
                { icon: 'translate', text: '每日20次翻译', included: true },
                { icon: 'mic', text: '每日5次语音识别', included: true },
                { icon: 'support', text: 'GPT-3.5模型', included: true },
                { icon: 'speed', text: '标准响应速度', included: true },
                { icon: 'cloud-off', text: '云端同步', included: false },
                { icon: 'star', text: 'GPT-4模型', included: false },
                { icon: 'headset', text: '优先客服支持', included: false },
            ],
        },
        {
            id: 'ai_tool_basic_monthly',
            name: '基础版',
            price: '¥19.9',
            period: '/月',
            color: ['#3498db', '#2980b9'],
            features: [
                { icon: 'chat', text: '每日100次AI对话', included: true },
                { icon: 'translate', text: '每日200次翻译', included: true },
                { icon: 'mic', text: '每日50次语音识别', included: true },
                { icon: 'support', text: 'GPT-3.5模型', included: true },
                { icon: 'speed', text: '快速响应', included: true },
                { icon: 'cloud-upload', text: '云端同步', included: true },
                { icon: 'star', text: 'GPT-4模型', included: false },
                { icon: 'headset', text: '优先客服支持', included: false },
            ],
        },
        {
            id: 'ai_tool_premium_monthly',
            name: '高级版',
            price: '¥59.9',
            period: '/月',
            color: ['#667eea', '#764ba2'],
            popular: true,
            features: [
                { icon: 'chat', text: '每日1000次AI对话', included: true },
                { icon: 'translate', text: '每日2000次翻译', included: true },
                { icon: 'mic', text: '每日500次语音识别', included: true },
                { icon: 'support', text: 'GPT-3.5模型', included: true },
                { icon: 'star', text: 'GPT-4模型访问', included: true },
                { icon: 'speed', text: '极速响应', included: true },
                { icon: 'cloud-upload', text: '云端同步', included: true },
                { icon: 'headset', text: '7×24小时客服', included: true },
            ],
        },
        {
            id: 'ai_tool_premium_yearly',
            name: '高级版年付',
            price: '¥599',
            period: '/年',
            color: ['#f39c12', '#e67e22'],
            savings: '省¥119',
            features: [
                { icon: 'chat', text: '每日1000次AI对话', included: true },
                { icon: 'translate', text: '每日2000次翻译', included: true },
                { icon: 'mic', text: '每日500次语音识别', included: true },
                { icon: 'support', text: 'GPT-3.5模型', included: true },
                { icon: 'star', text: 'GPT-4模型访问', included: true },
                { icon: 'speed', text: '极速响应', included: true },
                { icon: 'cloud-upload', text: '云端同步', included: true },
                { icon: 'headset', text: '专属客服经理', included: true },
            ],
        },
    ];

    const faqItems = [
        {
            question: '订阅后可以随时取消吗？',
            answer: '是的，您可以随时在订阅管理中取消订阅。取消后，您仍可以使用服务直到当前订阅期结束。',
        },
        {
            question: '如何更换订阅套餐？',
            answer: '您可以随时升级到更高级的套餐。如需降级，需要等待当前订阅期结束后再进行更改。',
        },
        {
            question: '支付方式有哪些？',
            answer: '我们支持Google Play支付，包括信用卡、借记卡、Google Play余额等多种支付方式。',
        },
        {
            question: '订阅会自动续费吗？',
            answer: '是的，订阅会在到期时自动续费。您可以在Google Play订阅管理中关闭自动续费。',
        },
        {
            question: '可以申请退款吗？',
            answer: '根据Google Play政策，购买后48小时内可以申请退款。具体请联系客服处理。',
        },
    ];

    useEffect(() => {
        loadProducts();
    }, []);

    const loadProducts = async () => {
        setIsLoading(true);
        try {
            const products = await billingService.getSubscriptions();
            setProducts(products);
        } catch (error) {
            console.error('Load products error:', error);
        } finally {
            setIsLoading(false);
        }
    };

    const handlePurchase = async (planId: string) => {
        if (planId === 'free') {
            // 免费版不需要购买
            return;
        }

        if (subscription?.plan === 'PREMIUM' && planId !== 'ai_tool_premium_yearly') {
            Alert.alert(
                '已是高级版',
                '您已经是高级版用户，无需重复购买',
                [{ text: '确定' }]
            );
            return;
        }

        Alert.alert(
            '确认购买',
            `确定要购买${plans.find(p => p.id === planId)?.name}吗？`,
            [
                { text: '取消', style: 'cancel' },
                {
                    text: '确定',
                    onPress: async () => {
                        setIsPurchasing(true);
                        try {
                            await billingService.purchaseSubscription(planId);
                            Toast.show({
                                type: 'success',
                                text1: '购买成功',
                                text2: '感谢您的支持！',
                            });

                            // 更新订阅状态
                            dispatch(updateSubscription({
                                plan: planId.includes('premium') ? 'PREMIUM' : 'BASIC',
                                expiryTime: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toISOString(),
                            }));
                        } catch (error: any) {
                            if (error.code !== 'E_USER_CANCELLED') {
                                Toast.show({
                                    type: 'error',
                                    text1: '购买失败',
                                    text2: error.message,
                                });
                            }
                        } finally {
                            setIsPurchasing(false);
                        }
                    },
                },
            ]
        );
    };

    const handleRestorePurchases = async () => {
        setIsLoading(true);
        try {
            await billingService.restorePurchases();
            Toast.show({
                type: 'success',
                text1: '恢复成功',
                text2: '您的购买已恢复',
            });
        } catch (error) {
            Toast.show({
                type: 'error',
                text1: '恢复失败',
                text2: '未找到可恢复的购买',
            });
        } finally {
            setIsLoading(false);
        }
    };

    const handleCancelSubscription = () => {
        Alert.alert(
            '取消订阅',
            '确定要取消订阅吗？取消后您仍可使用服务直到当前订阅期结束。',
            [
                { text: '取消', style: 'cancel' },
                {
                    text: '确定',
                    style: 'destructive',
                    onPress: async () => {
                        try {
                            // 跳转到Google Play订阅管理
                            Toast.show({
                                type: 'info',
                                text1: '请在Google Play中取消订阅',
                            });
                        } catch (error) {
                            Toast.show({
                                type: 'error',
                                text1: '操作失败',
                            });
                        }
                    },
                },
            ]
        );
    };

    const renderPlanCard = (plan: SubscriptionPlan) => {
        const isCurrentPlan = subscription?.plan ===
            (plan.id.includes('premium') ? 'PREMIUM' : plan.id.includes('basic') ? 'BASIC' : 'FREE');

        return (
            <TouchableOpacity
                key={plan.id}
                style={[
                    styles.planCard,
                    selectedPlan === plan.id && styles.planCardSelected,
                    isCurrentPlan && styles.planCardCurrent,
                ]}
                onPress={() => setSelectedPlan(plan.id)}
                activeOpacity={0.8}
            >
                {plan.popular && (
                    <View style={styles.popularBadge}>
                        <Text style={styles.popularText}>最受欢迎</Text>
                    </View>
                )}

                {isCurrentPlan && (
                    <View style={styles.currentBadge}>
                        <Text style={styles.currentText}>当前套餐</Text>
                    </View>
                )}

                <LinearGradient
                    colors={plan.color}
                    style={styles.planHeader}
                >
                    <Text style={styles.planName}>{plan.name}</Text>
                    <View style={styles.priceContainer}>
                        <Text style={styles.planPrice}>{plan.price}</Text>
                        <Text style={styles.planPeriod}>{plan.period}</Text>
                    </View>
                    {plan.savings && (
                        <View style={styles.savingsBadge}>
                            <Text style={styles.savingsText}>{plan.savings}</Text>
                        </View>
                    )}
                </LinearGradient>

                <View style={styles.featuresContainer}>
                    {plan.features.map((feature, index) => (
                        <View key={index} style={styles.featureItem}>
                            <Icon
                                name={feature.included ? 'check-circle' : 'cancel'}
                                size={20}
                                color={feature.included ? '#4caf50' : '#ccc'}
                            />
                            <Text style={[
                                styles.featureText,
                                !feature.included && styles.featureTextDisabled
                            ]}>
                                {feature.text}
                            </Text>
                        </View>
                    ))}
                </View>

                {selectedPlan === plan.id && (
                    <TouchableOpacity
                        style={[
                            styles.selectButton,
                            isCurrentPlan && styles.selectButtonDisabled,
                        ]}
                        onPress={() => handlePurchase(plan.id)}
                        disabled={isCurrentPlan || isPurchasing}
                    >
                        {isPurchasing && selectedPlan === plan.id ? (
                            <ActivityIndicator color="#fff" />
                        ) : (
                            <Text style={styles.selectButtonText}>
                                {isCurrentPlan ? '当前使用中' : '选择此套餐'}
                            </Text>
                        )}
                    </TouchableOpacity>
                )}
            </TouchableOpacity>
        );
    };

    return (
        <ScrollView style={styles.container} showsVerticalScrollIndicator={false}>
            {/* Header */}
            <LinearGradient
                colors={['#667eea', '#764ba2']}
                style={styles.header}
            >
                <Text style={styles.headerTitle}>选择适合您的套餐</Text>
                <Text style={styles.headerSubtitle}>
                    解锁更多功能，享受极致AI体验
                </Text>

                {subscription?.expiryTime && (
                    <View style={styles.currentPlanInfo}>
                        <Icon name="info" size={16} color="#fff" />
                        <Text style={styles.currentPlanText}>
                            当前套餐将于 {new Date(subscription.expiryTime).toLocaleDateString('zh-CN')} 到期
                        </Text>
                    </View>
                )}
            </LinearGradient>

            {/* Plans */}
            <View style={styles.plansContainer}>
                {isLoading ? (
                    <ActivityIndicator size="large" color="#667eea" style={styles.loader} />
                ) : (
                    plans.map(plan => renderPlanCard(plan))
                )}
            </View>

            {/* Benefits */}
            <View style={styles.benefitsSection}>
                <Text style={styles.benefitsTitle}>订阅特权</Text>
                <View style={styles.benefitsList}>
                    <View style={styles.benefitItem}>
                        <LinearGradient
                            colors={['#667eea', '#764ba2']}
                            style={styles.benefitIcon}
                        >
                            <Icon name="flash-on" size={24} color="#fff" />
                        </LinearGradient>
                        <View style={styles.benefitContent}>
                            <Text style={styles.benefitTitle}>极速响应</Text>
                            <Text style={styles.benefitDesc}>优先处理请求，响应速度提升300%</Text>
                        </View>
                    </View>

                    <View style={styles.benefitItem}>
                        <LinearGradient
                            colors={['#f39c12', '#e67e22']}
                            style={styles.benefitIcon}
                        >
                            <Icon name="all-inclusive" size={24} color="#fff" />
                        </LinearGradient>
                        <View style={styles.benefitContent}>
                            <Text style={styles.benefitTitle}>无限制使用</Text>
                            <Text style={styles.benefitDesc}>解除所有功能限制，畅享AI服务</Text>
                        </View>
                    </View>

                    <View style={styles.benefitItem}>
                        <LinearGradient
                            colors={['#27ae60', '#229954']}
                            style={styles.benefitIcon}
                        >
                            <Icon name="support-agent" size={24} color="#fff" />
                        </LinearGradient>
                        <View style={styles.benefitContent}>
                            <Text style={styles.benefitTitle}>专属客服</Text>
                            <Text style={styles.benefitDesc}>7×24小时专人服务，快速解决问题</Text>
                        </View>
                    </View>

                    <View style={styles.benefitItem}>
                        <LinearGradient
                            colors={['#e74c3c', '#c0392b']}
                            style={styles.benefitIcon}
                        >
                            <Icon name="new-releases" size={24} color="#fff" />
                        </LinearGradient>
                        <View style={styles.benefitContent}>
                            <Text style={styles.benefitTitle}>抢先体验</Text>
                            <Text style={styles.benefitDesc}>第一时间体验最新功能</Text>
                        </View>
                    </View>
                </View>
            </View>

            {/* Actions */}
            <View style={styles.actions}>
                <TouchableOpacity
                    style={styles.restoreButton}
                    onPress={handleRestorePurchases}
                >
                    <Icon name="restore" size={20} color="#667eea" />
                    <Text style={styles.restoreButtonText}>恢复购买</Text>
                </TouchableOpacity>

                {subscription?.plan !== 'FREE' && (
                    <TouchableOpacity
                        style={styles.cancelButton}
                        onPress={handleCancelSubscription}
                    >
                        <Text style={styles.cancelButtonText}>取消订阅</Text>
                    </TouchableOpacity>
                )}
            </View>

            {/* FAQ */}
            <TouchableOpacity
                style={styles.faqButton}
                onPress={() => setShowFAQ(true)}
            >
                <Icon name="help-outline" size={20} color="#667eea" />
                <Text style={styles.faqButtonText}>常见问题</Text>
            </TouchableOpacity>

            {/* FAQ Modal */}
            <Modal
                visible={showFAQ}
                transparent
                animationType="slide"
                onRequestClose={() => setShowFAQ(false)}
            >
                <View style={styles.modalOverlay}>
                    <View style={styles.modalContent}>
                        <View style={styles.modalHeader}>
                            <Text style={styles.modalTitle}>常见问题</Text>
                            <TouchableOpacity onPress={() => setShowFAQ(false)}>
                                <Icon name="close" size={24} color="#666" />
                            </TouchableOpacity>
                        </View>

                        <ScrollView style={styles.faqList}>
                            {faqItems.map((item, index) => (
                                <TouchableOpacity
                                    key={index}
                                    style={styles.faqItem}
                                    onPress={() => setExpandedFAQ(expandedFAQ === index ? null : index)}
                                >
                                    <View style={styles.faqQuestion}>
                                        <Text style={styles.faqQuestionText}>{item.question}</Text>
                                        <Icon
                                            name={expandedFAQ === index ? 'expand-less' : 'expand-more'}
                                            size={24}
                                            color="#666"
                                        />
                                    </View>
                                    {expandedFAQ === index && (
                                        <Text style={styles.faqAnswer}>{item.answer}</Text>
                                    )}
                                </TouchableOpacity>
                            ))}
                        </ScrollView>
                    </View>
                </View>
            </Modal>
        </ScrollView>
    );
};

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#f8f9fa',
    },
    header: {
        paddingTop: 50,
        paddingBottom: 30,
        paddingHorizontal: 20,
        alignItems: 'center',
    },
    headerTitle: {
        fontSize: 24,
        fontWeight: 'bold',
        color: '#fff',
        marginBottom: 10,
    },
    headerSubtitle: {
        fontSize: 16,
        color: 'rgba(255, 255, 255, 0.9)',
        textAlign: 'center',
    },
    currentPlanInfo: {
        flexDirection: 'row',
        alignItems: 'center',
        marginTop: 15,
        paddingVertical: 8,
        paddingHorizontal: 15,
        backgroundColor: 'rgba(255, 255, 255, 0.2)',
        borderRadius: 20,
    },
    currentPlanText: {
        fontSize: 14,
        color: '#fff',
        marginLeft: 8,
    },
    plansContainer: {
        padding: 20,
    },
    loader: {
        marginVertical: 50,
    },
    planCard: {
        backgroundColor: '#fff',
        borderRadius: 15,
        marginBottom: 15,
        overflow: 'hidden',
        shadowColor: '#000',
        shadowOffset: {
            width: 0,
            height: 2,
        },
        shadowOpacity: 0.1,
        shadowRadius: 3.84,
        elevation: 5,
    },
    planCardSelected: {
        borderWidth: 2,
        borderColor: '#667eea',
    },
    planCardCurrent: {
        borderWidth: 2,
        borderColor: '#4caf50',
    },
    popularBadge: {
        position: 'absolute',
        top: 10,
        right: 10,
        backgroundColor: '#ff6b6b',
        paddingHorizontal: 12,
        paddingVertical: 4,
        borderRadius: 12,
        zIndex: 1,
    },
    popularText: {
        color: '#fff',
        fontSize: 12,
        fontWeight: 'bold',
    },
    currentBadge: {
        position: 'absolute',
        top: 10,
        left: 10,
        backgroundColor: '#4caf50',
        paddingHorizontal: 12,
        paddingVertical: 4,
        borderRadius: 12,
        zIndex: 1,
    },
    currentText: {
        color: '#fff',
        fontSize: 12,
        fontWeight: 'bold',
    },
    planHeader: {
        padding: 20,
        alignItems: 'center',
    },
    planName: {
        fontSize: 20,
        fontWeight: 'bold',
        color: '#fff',
        marginBottom: 10,
    },
    priceContainer: {
        flexDirection: 'row',
        alignItems: 'baseline',
    },
    planPrice: {
        fontSize: 32,
        fontWeight: 'bold',
        color: '#fff',
    },
    planPeriod: {
        fontSize: 16,
        color: 'rgba(255, 255, 255, 0.9)',
        marginLeft: 5,
    },
    savingsBadge: {
        marginTop: 10,
        backgroundColor: 'rgba(255, 255, 255, 0.3)',
        paddingHorizontal: 12,
        paddingVertical: 4,
        borderRadius: 12,
    },
    savingsText: {
        color: '#fff',
        fontSize: 14,
        fontWeight: 'bold',
    },
    featuresContainer: {
        padding: 20,
    },
    featureItem: {
        flexDirection: 'row',
        alignItems: 'center',
        marginBottom: 12,
    },
    featureText: {
        fontSize: 14,
        color: '#333',
        marginLeft: 12,
        flex: 1,
    },
    featureTextDisabled: {
        color: '#999',
        textDecorationLine: 'line-through',
    },
    selectButton: {
        backgroundColor: '#667eea',
        paddingVertical: 15,
        alignItems: 'center',
    },
    selectButtonDisabled: {
        backgroundColor: '#ccc',
    },
    selectButtonText: {
        color: '#fff',
        fontSize: 16,
        fontWeight: 'bold',
    },
    benefitsSection: {
        padding: 20,
    },
    benefitsTitle: {
        fontSize: 20,
        fontWeight: 'bold',
        color: '#333',
        marginBottom: 20,
    },
    benefitsList: {
        backgroundColor: '#fff',
        borderRadius: 15,
        padding: 15,
    },
    benefitItem: {
        flexDirection: 'row',
        alignItems: 'center',
        marginBottom: 20,
    },
    benefitIcon: {
        width: 50,
        height: 50,
        borderRadius: 25,
        justifyContent: 'center',
        alignItems: 'center',
    },
    benefitContent: {
        flex: 1,
        marginLeft: 15,
    },
    benefitTitle: {
        fontSize: 16,
        fontWeight: '600',
        color: '#333',
        marginBottom: 5,
    },
    benefitDesc: {
        fontSize: 14,
        color: '#666',
        lineHeight: 20,
    },
    actions: {
        flexDirection: 'row',
        justifyContent: 'space-around',
        paddingHorizontal: 20,
        marginBottom: 20,
    },
    restoreButton: {
        flexDirection: 'row',
        alignItems: 'center',
        paddingVertical: 12,
        paddingHorizontal: 20,
        borderRadius: 25,
        backgroundColor: '#fff',
        borderWidth: 1,
        borderColor: '#667eea',
    },
    restoreButtonText: {
        fontSize: 14,
        color: '#667eea',
        marginLeft: 8,
        fontWeight: '600',
    },
    cancelButton: {
        paddingVertical: 12,
        paddingHorizontal: 20,
        borderRadius: 25,
        backgroundColor: '#fff',
        borderWidth: 1,
        borderColor: '#ff6b6b',
    },
    cancelButtonText: {
        fontSize: 14,
        color: '#ff6b6b',
        fontWeight: '600',
    },
    faqButton: {
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'center',
        marginBottom: 30,
    },
    faqButtonText: {
        fontSize: 14,
        color: '#667eea',
        marginLeft: 8,
    },
    modalOverlay: {
        flex: 1,
        backgroundColor: 'rgba(0, 0, 0, 0.5)',
        justifyContent: 'flex-end',
    },
    modalContent: {
        backgroundColor: '#fff',
        borderTopLeftRadius: 20,
        borderTopRightRadius: 20,
        height: '70%',
    },
    modalHeader: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        padding: 20,
        borderBottomWidth: 1,
        borderBottomColor: '#f0f0f0',
    },
    modalTitle: {
        fontSize: 18,
        fontWeight: 'bold',
        color: '#333',
    },
    faqList: {
        flex: 1,
        padding: 20,
    },
    faqItem: {
        marginBottom: 15,
        backgroundColor: '#f8f9fa',
        borderRadius: 10,
        padding: 15,
    },
    faqQuestion: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
    },
    faqQuestionText: {
        fontSize: 16,
        color: '#333',
        fontWeight: '600',
        flex: 1,
    },
    faqAnswer: {
        fontSize: 14,
        color: '#666',
        lineHeight: 20,
        marginTop: 10,
    },
});

export default SubscriptionScreen;